import 'package:ati_package/core/extension/ati_widgets_extension.dart';
import 'package:ati_package/core/utils/ati_assets.dart';
import 'package:ati_package/core/utils/ati_color.dart';
import 'package:ati_package/core/utils/ati_enum.dart';
import 'package:ati_package/core/utils/ati_font.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../personal_center/login_and_register/widgets/get_code_button.dart';
// import 'package:get/get_connect/http/src/utils/utils.dart';

class AtiTextInput extends StatefulWidget {
  final String name;
  final EdgeInsetsGeometry? padding;
  final Color? bgColor;
  final String? label;
  final String? hint;
  final String? initialValue;
  final bool enabled;
  final bool obscureText;
  final TextInputType? keyboardType;
  final TextInputAction? textInputAction;
  final int? maxLength;
  final int maxLines;
  final int minLines;
  final String? Function(String?)? validator;
  final void Function(String?)? onChanged;
  final void Function(String?)? onSubmitted;
  final bool showClearButton;
  final bool showObscureToggle;
  final bool? showPrefixIcon;
  final bool? showPrefixType; //ture:为icon   false:text
  final String? prefixLabel;
  final String? suffixLabel;
  final AtiInputType? inputType;
  final VoidCallback? onTap; // ✅ 新增：用于选择类型时点击触发
  final bool? showBorder;
  final double? radius;

  const AtiTextInput({
    super.key,
    required this.name,
    this.padding,
    this.bgColor, //= const Color(0xFFF5F7F8),
    this.label = '',
    this.hint,
    this.initialValue,
    this.enabled = true,
    this.obscureText = false,
    this.keyboardType,
    this.textInputAction,
    this.maxLength,
    this.maxLines = 1,
    this.minLines = 1,
    this.validator,
    this.onChanged,
    this.onSubmitted,
    this.showClearButton = false,
    this.showObscureToggle = false,
    this.showPrefixIcon = false,
    this.showPrefixType = false,
    this.prefixLabel = '',
    this.suffixLabel = '',
    this.inputType,
    this.onTap,
    this.showBorder = true,
    this.radius = 6,
  });

  @override
  State<AtiTextInput> createState() => _AtiTextInputState();
}

class _AtiTextInputState extends State<AtiTextInput> {
  late TextEditingController _controller;
  late FocusNode _focusNode;
  late bool _obscureText;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.initialValue ?? '');
    _focusNode = FocusNode();
    _obscureText = widget.obscureText;
    _focusNode.addListener(() {
      setState(() {}); // 监听焦点变化，刷新边框颜色
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _toggleObscure() => setState(() => _obscureText = !_obscureText);

  void _clearText() {
    _controller.clear();
    widget.onChanged?.call('');
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    Color borderColor;
    if (_hasError) {
      borderColor = Colors.red;
    } else if (_focusNode.hasFocus) {
      borderColor = AtiColor.primary; // 聚焦时主色
    } else {
      borderColor = Colors.transparent; // 默认无边框
    }

    return Container(
      padding: widget.padding ?? EdgeInsets.symmetric(vertical: 7.5.r),
      decoration: BoxDecoration(
        color: widget.bgColor,
        borderRadius: BorderRadius.all(Radius.circular(12.r)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (widget.label!.isNotEmpty) ...[
            Text(
              widget.label ?? '',
              style: TextStyle(
                fontSize: 14.r,
                fontWeight: FontWeight.w600,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 8),
          ],

          AbsorbPointer(
            absorbing: widget.inputType == AtiInputType.select,
            child: FormBuilderTextField(
              name: widget.name,
              controller: _controller,
              focusNode: _focusNode,
              enabled: widget.enabled,
              readOnly: (widget.inputType == AtiInputType.select)
                  ? true
                  : false,
              obscureText: _obscureText,
              keyboardType: widget.keyboardType,
              textInputAction: widget.textInputAction,
              maxLength: widget.maxLength,
              maxLines: widget.maxLines,
              minLines: widget.minLines,
              validator: (val) {
                final error = widget.validator?.call(val);
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  if (mounted) setState(() => _hasError = error != null);
                });
                return error;
              },
              onChanged: (val) {
                widget.onChanged?.call(val);
                setState(() {});
              },
              onSubmitted: widget.onSubmitted,
              decoration: InputDecoration(
                hintText: widget.hint ?? '请填写',
                hintStyle: TextStyle(color: Colors.grey, fontSize: 13.r),
                filled: true,
                fillColor: Colors.white,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 12.5.r,
                  vertical: 12.5.r,
                ),
                border: !widget.showBorder! ? InputBorder.none : null,
                enabledBorder: widget.showBorder!
                    ? OutlineInputBorder(
                        borderRadius: BorderRadius.circular(widget.radius!.r),
                        borderSide: BorderSide(color: Colors.grey.shade300),
                      )
                    : null,
                focusedBorder: widget.showBorder!
                    ? OutlineInputBorder(
                        borderRadius: BorderRadius.circular(widget.radius!.r),
                        borderSide: BorderSide(color: borderColor, width: 1.6),
                      )
                    : null,
                errorBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(widget.radius!.r),
                  borderSide: const BorderSide(color: Colors.red, width: 1.6),
                ),
                focusedErrorBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(widget.radius!.r),
                  borderSide: const BorderSide(color: Colors.red, width: 1.6),
                ),
                prefixIcon: _buildPrefixIcons(),
                suffixIcon: _buildSuffixIcons(),
                suffixIconConstraints: BoxConstraints(
                  // minWidth: 20.r,
                  // minHeight: 20.r,
                  // maxWidth: 120.r,
                  // maxHeight: 25.r,
                ),
              ),
            ),
          ).addTapGesture(
            onTap: () {
              if (widget.inputType == AtiInputType.select) {
                FocusScope.of(context).unfocus(); // 收起键盘
                widget.onTap?.call();
                print('我被点击了');
                // ✅ 调用自定义点击事件
              }
            },
          ),
        ],
      ),
    );
  }

  Widget? _buildSuffixIcons() {
    final icons = <Widget>[];
    // 清除按钮
    if (widget.showClearButton && _controller.text.isNotEmpty) {
      icons.add(
        Container(
          constraints: BoxConstraints(
            minWidth: 20.r,
            minHeight: 20.r,
            maxWidth: 80.r,
            maxHeight: 22.5.r,
          ),
          padding: EdgeInsets.symmetric(horizontal: 12.5.r),
          child: Image.asset(
            AtiAssets.atiDeleteIcon,
            package: 'ati_package',
            color: _focusNode.hasFocus ? AtiColor.primary : Color(0xFF666666),
          ),
        ).addTapGesture(onTap: _clearText),
      );
    }

    if (widget.inputType == AtiInputType.select) {
      icons.add(
        Container(
          padding: EdgeInsets.symmetric(horizontal: 12.5.r),
          child: Image.asset(
            AtiAssets.atiDownIcon,
            package: 'ati_package',
            color: _focusNode.hasFocus ? AtiColor.primary : Color(0xFF666666),
          ),
        ).addTapGesture(onTap: _clearText),
      );
    }

    if (widget.inputType == AtiInputType.textCode) {
      icons.add(
        GetCodeButton(
          onSend: () async {
            widget.onTap?.call();
            await Future.delayed(const Duration(seconds: 1));
            return true; // true 表示发送成功
          },
        ),
      );
    }
    if (widget.suffixLabel!.isNotEmpty) {
      icons.add(
        Container(
          padding: EdgeInsets.only(right: 16.r),
          height: 30.r,
          alignment: Alignment.centerRight,
          child: Text(
            widget.suffixLabel!,
            style: TextStyle(
              color: Colors.black,
              fontSize: AtiFont.font14,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      );
    }

    // 密码显示/隐藏按钮
    if (widget.showObscureToggle) {
      print('_obscureText = ${_obscureText}');
      icons.add(
        Container(
          margin: EdgeInsets.only(),
          padding: EdgeInsets.symmetric(horizontal: 12.5.r),
          child: Image.asset(
            _obscureText ? AtiAssets.atiEyeOpent : AtiAssets.atiEyeColse,
            package: 'ati_package',
            color: Color(0xFF666666),
          ).addTapGesture(onTap: () => _toggleObscure()),
        ),
      );
    }

    if (icons.isEmpty) return null;
    if (icons.length == 1) return icons.first;
    return Row(mainAxisSize: MainAxisSize.min, children: icons);
  }

  _buildPrefixIcons() {
    if (widget.showPrefixIcon!) {
      if (widget.showPrefixType!) {
        return Container(
          padding: EdgeInsets.only(right: 12.5.r),
          child: Image.asset(
            width: 24.r,
            height: 24.r,
            widget.prefixLabel!,
            package: 'ati_package',
          ),
        );
      }
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 7.5.r),
        width: 75.r,
        height: 30.r,
        alignment: Alignment.center,
        child: Text(
          widget.prefixLabel!,
          style: TextStyle(
            color: Colors.black,
            fontSize: AtiFont.font14,
            fontWeight: FontWeight.w600,
          ),
        ),
      );
    }
    return null;
  }
}
